--
-- DailyTaskView.lua
-- Created by IntelliJ IDEA.
-- User: yao.chen
-- Date: 2018/12/27
--

local ClassRef = app.mvc.createPanelClass(...)
local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local NewDailyTaskRender = import(".renders.NewDailyTaskRender")

local percent_1_start = 27
local percent_1_end = 34
local percent_2_start = 62
local percent_2_end = 68
local percent_3 = 100

function ClassRef.createWithData(data, node)
    local res
    local publisher = app:getInnerPublisher()
    if publisher == Enums.Publisher.ema then
        res = Res.DailyNodeTask_EN
    elseif publisher == Enums.Publisher.tencent then
        res = Res.DailyNodeTask
    else
        res = Res.DailyNodeTask
    end

    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(res))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end

function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

function ClassRef:init(data)
    self.super.init(self, data)

    self._dailyListView = self._ui["Panel/Panel_data/ListView"]
    self._dailyListView:removeAllItems()

    self._giftPanel1 = self._ui["Panel/Panel_bom/reward_1/Panel"]  -- 引导的时候会把该node移除掉，所以这里先暂存

    if app:getInnerPublisher() == Enums.Publisher.ema then
        self._privilegePanel = self._ui.Panel_gift
    end

    self._isPrivilege = false

    self._ui["Panel/Panel_bom/Text"]:setString(L("taskaccumulation"))
end

function ClassRef:refresh()
    local items = self._dailyListView:getItems()
    if #items > 0 then
        self._dailyListView:removeAllItems()
    end

    local dailyTasks = executeFunc(self._onOperate, "getDailyTasks")
    local len = math.modf(#dailyTasks / 2) + math.fmod(#dailyTasks, 2)
    local index = 1
    for i = 1, len do
        local render = NewDailyTaskRender.create()
        render:onBtnClick(self._onOperate)
        local tempData = {dailyTasks[index], dailyTasks[index + 1]}
        render:setData(tempData)
        index = index + 2
        self._dailyListView:pushBackCustomItem(render)
    end
    self._dailyListView:refreshView()

    -- 设置LoadingBar初始进度为0
    local loadingBar = self._ui["Panel/Panel_bom/bar/LoadingBar"]
    loadingBar:setPercent(0)

end

function ClassRef:updateDailyTasksShow(taskId)
    if not taskId then return end

    local taskInfo = UD:getTaskById(taskId)
    if not taskInfo then return end

    local items = self._dailyListView:getItems()
    for _, item in ipairs(items) do
        local t_taskId = item:getId()
        for i = 1, #t_taskId do
            if t_taskId[i] == taskId then
                item:setDataWithIndex(taskInfo, i)
                break
            end
        end
    end
end

function ClassRef:updatePrivilegeInfo(msg)
    self._isPrivilege = msg.SuperPrivilegeDays > 0
    self._SuperPrivilegeID = msg.SuperPrivilegeID
    self._SuperPrivilegeGoods = msg.GoodsInfo
    self._SuperPrivilegeDrop = msg.Drop

    self:refreshPrivilegeBox()
end

function ClassRef:refreshPrivilegeBox(msg)
    if not self._privilegePanel then return end

    local boxNum = 0
    local canGet = 0
    if msg then
        boxNum = msg.SuperPrivilegeBoxNum
        canGet = msg.CanGetSuperPrivilegeBox
    else
        local dailyTaskInfo = TaskManager:getDailyTaskInfo()
        boxNum = dailyTaskInfo:getSuperPrivilegeBoxNum()
        canGet = dailyTaskInfo:CanGetSuperPrivilegeBox()
    end

    --ui
    local _maskLock = self._privilegePanel:getChildByName("mask_lock")
    local _iconCanOpen = self._privilegePanel:getChildByName("icon_1")
    local _iconCantOpen = self._privilegePanel:getChildByName("icon_no")
    local _iconOpened = self._privilegePanel:getChildByName("icon_open")
    local _numBgBlack = self._privilegePanel:getChildByName("bg_num2")
    local _numBgRed = self._privilegePanel:getChildByName("bg_num3")
    local _boxNum = self._privilegePanel:getChildByName("num_2")

    local t_ui = {_maskLock, _iconCanOpen, _iconCantOpen, _iconOpened, _numBgBlack, _numBgRed, _boxNum}
    for _, v in pairs(t_ui) do
        v:setVisible(false)
    end

    if self._isPrivilege then
        if canGet > 0 then
            if boxNum > 0 then
                _iconCanOpen:setVisible(true)
                _numBgRed:setVisible(true)
                _boxNum:setVisible(true)
                _boxNum:setString(boxNum)
            else
                _iconOpened:setVisible(true)
            end
        else
            if boxNum > 0 then
                _numBgBlack:setVisible(true)
                _boxNum:setVisible(true)
                _boxNum:setString(boxNum)
            end
            _iconCanOpen:setVisible(true)
            _maskLock:setVisible(true)
        end
    else
        _iconCantOpen:setVisible(true)
        _numBgBlack:setVisible(true)
        _boxNum:setVisible(true)
        _boxNum:setString(boxNum)
    end


    local openbox = function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local param = {}
            param.isPrivilege = self._isPrivilege
            param.isLock = canGet <= 0
            param.isGet = boxNum > 0
            param.drop = self._SuperPrivilegeDrop
            executeFunc(self._onOperate, "OPEN_PRIVILEGE_BOX", param)
        end
    end

    if canGet > 0 then
        if boxNum <= 0 then
            openbox = function(sender, eventType)
                if eventType == ccui.TouchEventType.began then
                    local dataInfoTemp = {
                        name = L("privilegeBoxName"),
                        string1 = L("privilegeBoxDes"),
                        string4 = L("privilegeBoxWarning"),
                    }
                    if self._privilegeBoxInfoPanel then
                        self._privilegeBoxInfoPanel:setData(dataInfoTemp)
                    else
                        self._privilegeBoxInfoPanel = NewRareInfoView.create()
                        self._privilegeBoxInfoPanel:setData(dataInfoTemp)
                        UIHandler:addPopupUi(self._privilegeBoxInfoPanel)
                    end
                    local triggerNodeBoundingBox = self._privilegePanel:getBoundingBox()
                    local worldPosTemp = self._privilegePanel:getParent():convertToWorldSpace(cc.p(triggerNodeBoundingBox.x, triggerNodeBoundingBox.y))
                    triggerNodeBoundingBox.x = worldPosTemp.x
                    triggerNodeBoundingBox.y = worldPosTemp.y
                    display.adjustNodePos(triggerNodeBoundingBox, self._privilegeBoxInfoPanel)
                elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
                    if self._privilegeBoxInfoPanel then
                        self._privilegeBoxInfoPanel:removeFromParent()
                        self._privilegeBoxInfoPanel = nil
                    end
                end
            end
        end
    end

    _iconCanOpen:addTouchEventListener(openbox)
    _iconOpened:addTouchEventListener(openbox)
    _iconCantOpen:addTouchEventListener(openbox)
    _maskLock:addTouchEventListener(openbox)
end

function ClassRef:updateDailyTaskProgress()
    -- print("updateDailyTaskProgress")

    local dailyTasks = executeFunc(self._onOperate, "getDailyTasks")
    self:updateNewTasks(dailyTasks, true)

    local Panel_bom = self._ui["Panel/Panel_bom"]
    local progressBar = self._ui["Panel/Panel_bom/bar/LoadingBar"]
    local finishedNumText = Panel_bom:getChildByName("num")

    local totalNumber = executeFunc(self._onOperate, "getTotalDailyTaskNumber")
    local finishedNumber = executeFunc(self._onOperate, "getFinishedDailyTaskNumber")

    local dailyTaskInfo = TaskManager:getDailyTaskInfo()
    local progress = dailyTaskInfo:getDailyTaskProgress()
    local arrStr = {progress[1].NeedProgress, progress[2].NeedProgress, progress[3].NeedProgress}
    local value1, value2, value3 = tonumber(arrStr[1]), tonumber(arrStr[2]), tonumber(arrStr[3])

    local percent = finishedNumber / totalNumber * 100
    if finishedNumber <= value1 then
        percent = percent_1_start * (finishedNumber / value1)
    elseif finishedNumber <= value2 then
        percent = percent_1_end + ( percent_2_start - percent_1_end ) * ((finishedNumber - value1) / (value2 - value1))
    else
        percent = percent_2_end + ( percent_3 - percent_2_end ) * ((finishedNumber - value2) / (value3 - value2))
    end

    progressBar:setPercent(percent)
    finishedNumText:setString(finishedNumber)

    for i = 1, 3 do
        local name = "reward_" .. i
        local giftPanel
        if i == 1 then
            giftPanel = self._giftPanel1
        else
            local giftNode = Panel_bom:getChildByName(name)
            giftPanel = giftNode:getChildByName("Panel")
        end

        local maskLock = giftPanel:getChildByName("mask_lock")
        maskLock:setVisible(false)
        maskLock:setTouchEnabled(false)

        for j = 1, 3 do
            local boxName = "icon_" .. j
            local boxIcon = giftPanel:getChildByName(boxName)
            boxIcon:setVisible(false)

            boxName = "icon_".. j .. "_o"
            boxIcon = giftPanel:getChildByName(boxName)
            boxIcon:setVisible(false)
        end

        local bottomNumText = giftPanel:getChildByName("num_1")
        local getNumText = giftPanel:getChildByName("num_2")
        local blackBg = giftPanel:getChildByName("bg_num2")
        local redBg = giftPanel:getChildByName("bg_num3")
        getNumText:setVisible( false )
        blackBg:setVisible(false)
        redBg:setVisible(false)

        local rewardProgress = self._onOperate("getDailyTaskRewardProgress", tonumber(arrStr[i]))
        if rewardProgress then
            bottomNumText:setString( rewardProgress.NeedProgress )
            getNumText:setString( rewardProgress.NowProgress )

            if rewardProgress.NowProgress > 0 then -- 奖励累积次数 > 0？
                getNumText:setVisible(rewardProgress.NowProgress > 1)
                giftPanel:getChildByName("icon_" .. i):setVisible(true)

                local isLock = false
                if finishedNumber < tonumber(rewardProgress.NeedProgress) then -- 未解锁
                    isLock = true
                    blackBg:setVisible(rewardProgress.NowProgress > 1)
                    maskLock:setVisible(true)
                else
                    redBg:setVisible(true)
                end

                giftPanel:setTouchEnabled(true)
                giftPanel:addClickEventListener(function(sender)
                    local params = {}
                    params.isLock = isLock
                    params.nowProgress = rewardProgress.NowProgress
                    params.needProgress = rewardProgress.NeedProgress
                    params.boxIndex = rewardProgress.boxIndex
                    params.questType = 5
                    executeFunc(self._onOperate, "OPEN_REWARD", params)
                end)
            else
                giftPanel:getChildByName("icon_"..i.."_o"):setVisible(true)
                giftPanel:setTouchEnabled(true)
                giftPanel:addClickEventListener(function(sender)end)
                giftPanel:addTouchEventListener(function(sender, eventType)
                    if eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
                        local dataInfoTemp = {
                            name = L("dailyTreasureName"),
                            string1 = string.format(L("dailyTreasureDes"),S("daystartsat")),
                            string3 = L("restrictedreward2_3"),
                            string4 = L("dailyTreasureWarning"),
                        }
                        if self._rareInfoPanel then
                            self._rareInfoPanel:setData( dataInfoTemp )
                        else
                            self._rareInfoPanel = NewRareInfoView.create()
                            self._rareInfoPanel:setData( dataInfoTemp )
                            self._ui["Panel"]:addChild( self._rareInfoPanel )
                            --UIHandler:addPopupUi(self._rareInfoPanel)
                            -- 点击空白区域关闭
                            display.nodeRemoveForNotHit(self._rareInfoPanel, function()
                                if self._rareInfoPanel then
                                    self._rareInfoPanel:removeFromParent()
                                    self._rareInfoPanel = nil
                                end
                            end)
                        end
                        local triggerNodeBoundingBox = giftPanel:getBoundingBox()
                        local worldPosTemp = giftPanel:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
                        triggerNodeBoundingBox.x = worldPosTemp.x
                        triggerNodeBoundingBox.y = worldPosTemp.y
                        display.adjustNodePos( triggerNodeBoundingBox, self._rareInfoPanel )
                    -- elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
                    --     if self._rareInfoPanel then
                    --         self._rareInfoPanel:removeFromParent()
                    --         self._rareInfoPanel = nil
                    --     end
                    end
                end)
            end
        end
    end
end

function ClassRef:updateNewTasks(tasks, notSend)
    local hasFinish = false
    local items = self._dailyListView:getItems()
    for _, item in ipairs(items) do
        local t_taskId = item:getId()

        for _, task in pairs(tasks) do
            local lvTaskId = task:getId()
            for i = 1, #t_taskId do
                if lvTaskId == t_taskId[i] then
                    item:setDataWithIndex(task, i)

                    if task:isFinished() then
                        hasFinish = true
                    end
                    break
                end
            end
        end
    end

    -- 如果有日常任务完成，需要重新拉取完成进度
    if hasFinish and not notSend then
        executeFunc(self._onOperate, "GET_DAILY_INFO")
    end
end

function ClassRef:refreshDailyTask(pos)
    local task = UD:getDailytTaskByPos(pos)
    if not task then return end
    local items = self._dailyListView:getItems()
    for _, item in ipairs(items) do
        local t_taskPos = item:getPos()
        for i = 1, #t_taskPos do
            if pos == t_taskPos[i] then
                item:setDataWithIndex(task, i)
            end
        end
    end
end

function ClassRef:playDailyRefreshAni(pos)
    local render
    local items = self._dailyListView:getItems()
    for _, item in ipairs(items) do
        local t_taskPos = item:getPos()
        for i = 1, #t_taskPos do
            if t_taskPos[i] == pos then
                render = item:getRenderByIndex(i)
                break
            end
        end
    end
    if not render then return end

    local _aniTempNode = render:getChildByName("_refreshAnimationTemp")
    if _aniTempNode then
        render:removeChildByName("_refreshAnimationTemp")
    end
    local amiNodeTemp = cc.CSLoader:createNode(Res.DailyTaskRefreshAmi4)
    amiNodeTemp:setName("_refreshAnimationTemp" )
    amiNodeTemp:setPosition(render:getChildByName("ani_refresh"):getPosition())
    render:addChild(amiNodeTemp)
    amiNodeTemp:getTimeline():gotoFrameAndPlay(0, false)

    local actions = {}
    table.insert( actions, cc.DelayTime:create(amiNodeTemp:getTimeline():getDuration()/60 * 0.5))
    table.insert( actions, cc.CallFunc:create(function() self:refreshDailyTask(pos) end ))
    table.insert( actions, cc.DelayTime:create(amiNodeTemp:getTimeline():getDuration()/60 * 0.5))
    table.insert( actions, cc.CallFunc:create(function() amiNodeTemp:removeFromParent() end ))
    table.insert( actions, cc.RemoveSelf:create())
    amiNodeTemp:runAction(cc.Sequence:create(actions))
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

return ClassRef

